package com.childmiles.gwt.client.ui.awards;

import com.childmiles.gwt.client.Presenter;
import com.childmiles.gwt.client.domain.AwardWinner;
import com.childmiles.gwt.client.service.AwardWinnerServiceAsync;
import com.childmiles.gwt.client.ui.AwardPanel;
import com.childmiles.gwt.client.ui.EditAwardsDialog;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.Cell;

public class AwardsPresenter implements Presenter {

    private final AwardWinnerServiceAsync awardWinnerService;

    private final HandlerManager eventBus;

    private final Display display;

    public interface Display {
        Widget asWidget();

        HasText getAwardWinnerNameLabel();

        void setAwardWinner(AwardWinner awardWinner);
        
        FlexTable getAwardsTable();
        
        FlexTable.Cell getCellForEvent(ClickEvent event);
    }

    public AwardsPresenter(AwardWinnerServiceAsync awardWinnerService, HandlerManager eventBus, Display display) {
        this.awardWinnerService = awardWinnerService;
        this.eventBus = eventBus;
        this.display = display;
    }

    
    //TODO uh oh, GWT GUI stuff leaking out here (Cell, AwardPanel).  How can we fix this?
    public void bind(final AwardWinner awardWinner) {
        display.getAwardsTable().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                Cell cellForEvent = display.getAwardsTable().getCellForEvent(event);
                if (cellForEvent == null) {
                    return;
                }
                int rowIndex = cellForEvent.getRowIndex();
                int colIndex = cellForEvent.getCellIndex();
                if (rowIndex == 0 && colIndex == 0) {
                    //TODO
                    //for AwardWinnerImage go to settings screen
//                    createAndShowSettingsPanel();
                    return;
                }
                AwardPanel awardPanel = (AwardPanel) display.getAwardsTable().getWidget(rowIndex,colIndex);
                EditAwardsDialog editAwardsDialog = new EditAwardsDialog(awardWinnerService, awardWinner, awardPanel);
                editAwardsDialog.addStyleName("editAwardsDialog");
                editAwardsDialog.show();
            }
        });

    }

    //Have to bind after setData().  
    public void setData(AwardWinner awardWinner) {
        display.getAwardWinnerNameLabel().setText(awardWinner.getName());
        display.setAwardWinner(awardWinner);
        bind(awardWinner);
    }

    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }

}
